package com.itheima.interceptor;


import com.itheima.utils.CurrentHolder;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
/*
        //1.获取URL
        String url = request.getRequestURI().toString();

        //2.若URL中包含login，则放行
        if(url.contains("login")){
            log.info("登录请求，放行");
            return true;
        }
*/

        //3.获取请求头中的token
        String token = request.getHeader("token");

        //4.token为空，响应401
        if(token == null || token.isEmpty()){
            log.info("请求头中无token信息，返回401");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }

        //5.校验token，若校验失败，响应401
        try {
            JwtUtils.parseJWT(token);
            //从令牌获取id
            Claims claims = JwtUtils.parseJWT(token);
            Integer id = (Integer) claims.get("id");
            CurrentHolder.setCurrentId(id);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析token失败，返回401");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        //6.不为空且校验成功，放行
        log.info("token不为空且合法，放行");
        return true;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }
}
